package com.hs.jhzd.controller;

import com.hs.jhzd.entity.*;
import com.hs.jhzd.entity.dto.Xljg;
import com.hs.jhzd.repository.*;
import com.hs.jhzd.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 心理评测.
 *
 * @author neirol
 */

@Controller
@RequestMapping("/acp-cloud/assess")
public class Scl90ReviewController {
    @Value("${jsbh}")
    private String jsbh;

    @Value("${jsmc}")
    private String jsmc;

    @Autowired
    private JhScl90JgbRepository jhScl90JgbRepository;

    @Autowired
    private JhScl90DtjlbRepository jhScl90DtjlbRepository;

    @Autowired
    private XlzxstRepository xlzxstRepository;

    @Autowired
    private XlpgdtbRepository xlpgdtbRepository;
    @Autowired
    private PrisonerRepository prisonerRepository;

    public static final String DATE_FORMAT1 = "yyyy-MM-dd HH:mm:ss";

    @RequestMapping("/xl/list")
    @ResponseBody
    public List<JhXlzxstEntity> getAll() {
        return xlzxstRepository.findByLx("2");
    }

    @RequestMapping("/xl/save")
    @ResponseBody
    /*
    prisonId 监所编号
    number 人员编号
     */
    public boolean answer(@RequestParam(required = true) String prisonId,
                          @RequestParam(required = true) String number, @RequestParam(required = true) String answers) {
        String[] answerArr = answers.split(",");
        saveanswer(prisonId, number, answerArr);
        return true;
    }

    /*
    心理评估结果查询
     */
    @RequestMapping("/xl/resultQuery")
    @ResponseBody
    public List<Xljg> resultQuery(String rybh, String jsbh, @DateTimeFormat(pattern = DATE_FORMAT1) Date startTime,
                                              @DateTimeFormat(pattern = DATE_FORMAT1) Date endTime) {
       List<Xljg>result=  jhScl90JgbRepository.findByZybhAndJshAndSjcBetween(rybh,jsbh,startTime,endTime);
        return result;
    }
    /*
        心理评估结果查询返回页面
     */
    @RequestMapping("/admin/main")
    public String shiftMainPage(Model model, String name, String jsbh, @DateTimeFormat(pattern = DATE_FORMAT1) Date startTime,
                                @DateTimeFormat(pattern = DATE_FORMAT1) Date endTime) {
        List<Xljg> result=new ArrayList<>();
        if(StringUtils.isNotBlank(name)){
            List<Prisoner> byName = prisonerRepository.findByName(name);
            for (int i = 0; i <byName.size() ; i++) {
                result.addAll(jhScl90JgbRepository.findByZybhAndJshAndSjcBetween(byName.get(i).getRybh(),jsbh,startTime,endTime))  ;
            }
        }else {
            result.addAll( jhScl90JgbRepository.findByZybhAndJshAndSjcBetween(null,jsbh,startTime,endTime));
        }
        model.addAttribute("jsbh", jsbh);
        model.addAttribute("results", result);
        return "review-list";
    }


    /**
     * 回答问卷.
     *
     * @param prisonId  监所编号
     * @param number    人员编号
     * @param answerArr 所有答案
     */
    public void saveanswer(String prisonId, String number, String[] answerArr) {
        //String[] answerArr = answers.split(",");
        if (answerArr == null || answerArr.length != 90) {
            throw new IllegalArgumentException("SCL90心理评测答案长度异常！");
        }
        Date createTime = new Date();
        String finalResultId = prisonId + convert2Id12(createTime);
        collect(prisonId, number, answerArr, finalResultId, createTime);
        saveMultipleAnswer(prisonId, number, answerArr, finalResultId, createTime);
    }
    public void saveMultipleAnswer(String prisonId, String number, String[] answerArr, String finalResultId,
                                    Date createTime) {
        List<XlpgdtbEntity> list = new ArrayList<>();
        String time = DateFormatUtils.format(createTime, "yyyyMMddHHmmss");
        for (int i = 0; i < (answerArr.length - 1); i++) {
            XlpgdtbEntity xlpgdtbEntity = new XlpgdtbEntity();
            String zybh = prisonId + convert2Id12(new Date());
            xlpgdtbEntity.setZybh(zybh);
            xlpgdtbEntity.setRybh(number);
            xlpgdtbEntity.setFlid(TEST_TYPE);
            xlpgdtbEntity.setTmid(i + "");
            xlpgdtbEntity.setXx(answerArr[i]);
            xlpgdtbEntity.setFz(answerArr[i]);
            xlpgdtbEntity.setDtjs(time);
            xlpgdtbEntity.setFzybh(finalResultId);
            list.add(xlpgdtbEntity);
        }
        String zybh = prisonId + convert2Id12(new Date());
        XlpgdtbEntity xlpgdtbEntity = new XlpgdtbEntity();
        xlpgdtbEntity.setZybh(zybh);
        xlpgdtbEntity.setRybh(number);
        xlpgdtbEntity.setFlid(TEST_TYPE);
        xlpgdtbEntity.setTmid((answerArr.length - 1) + "");
        xlpgdtbEntity.setXx(answerArr[answerArr.length - 1]);
        xlpgdtbEntity.setFz(answerArr[answerArr.length - 1]);
        xlpgdtbEntity.setDtjs(time);
        xlpgdtbEntity.setFzybh(finalResultId);
        list.add(xlpgdtbEntity);
        xlpgdtbRepository.saveAll(list);
    }

    private void collect(String prisonId, String number, String[] answerArr, String finalResultId,
                         Date createTime) {
        StringBuilder sb = new StringBuilder();
        double totalScores = 0;
        double bodyScore = sum(answerArr, BODY_INDEX);
        double obsessiveScore = sum(answerArr, OBSESSIVE_INDEX);
        double relationShipScore = sum(answerArr, RELATIONSHIP_INDEX);
        double depressionScore = sum(answerArr, DEPRESSION_INDEX);
        double anxietyScore = sum(answerArr, ANXIETY_INDEX);
        double hostileScore = sum(answerArr, HOSTILE_INDEX);
        double terrorScore = sum(answerArr, TERROR_INDEX);
        double paranoidScore = sum(answerArr, PARANOID_INDEX);
        double psychosisScore = sum(answerArr, PSYCHOSIS_INDEX);
        double otherScore = sum(answerArr, OTHER_INDEX);

        totalScores = bodyScore + obsessiveScore + relationShipScore + depressionScore + anxietyScore
                + hostileScore + terrorScore + paranoidScore + psychosisScore + otherScore;

        sb.append(RESULT_START).append(RESULT_COLLECT);
        sb.append("总分是").append(totalScores).append(";").append(WRAP);
        sb.append(RESULT_BODY).append(getSingleResult(bodyScore / BODY_INDEX.length, BODY_RESULT))
                .append(WRAP);
        sb.append(RESULT_OBSESSIVE)
                .append(getSingleResult(obsessiveScore / OBSESSIVE_INDEX.length, OBSESSIVE_RESULT))
                .append(WRAP);
        sb.append(RESULT_RELATION)
                .append(getSingleResult(relationShipScore / RELATIONSHIP_INDEX.length, RELATION_RESULT))
                .append(WRAP);
        sb.append(RESULT_DEPRESSION)
                .append(getSingleResult(depressionScore / DEPRESSION_INDEX.length, DEPRESSION_RESULT))
                .append(WRAP);
        sb.append(RESULT_ANXIETY)
                .append(getSingleResult(anxietyScore / ANXIETY_INDEX.length, ANXIETY_RESULT)).append(WRAP);
        sb.append(RESULT_HOSTILE)
                .append(getSingleResult(hostileScore / HOSTILE_INDEX.length, HOSTILE_RESULT)).append(WRAP);
        sb.append(RESULT_TERROR)
                .append(getSingleResult(terrorScore / TERROR_INDEX.length, TERROR_RESULT)).append(WRAP);
        sb.append(RESULT_PARANOID)
                .append(getSingleResult(paranoidScore / PARANOID_INDEX.length, PARANOID_RESUTL))
                .append(WRAP);
        sb.append(RESULT_PSYCHOSIS)
                .append(getSingleResult(psychosisScore / PSYCHOSIS_INDEX.length, PSYCHOSIS_RESULT))
                .append(WRAP);
        sb.append(RESULT_OTHER).append(getSingleResult(otherScore / OTHER_INDEX.length, OTHER_RESUTL))
                .append(WRAP);

        
        JhScl90JgbEntity jhScl90Jgb = new JhScl90JgbEntity();
        jhScl90Jgb.setZybh(finalResultId);
        jhScl90Jgb.setJsbh(prisonId);
        jhScl90Jgb.setJsmc(jsmc);
        jhScl90Jgb.setRybh(number);
        jhScl90Jgb.setQth(String.valueOf(bodyScore));
        jhScl90Jgb.setQt(String.valueOf(otherScore));
        jhScl90Jgb.setJsbx(String.valueOf(psychosisScore));
        jhScl90Jgb.setPz(String.valueOf(paranoidScore));
        jhScl90Jgb.setKssj(DateUtils.geiTime());
        jhScl90Jgb.setZfz(String.valueOf(totalScores));
        jhScl90Jgb.setYy(String.valueOf(depressionScore));
        jhScl90Jgb.setRjgxmg(String.valueOf(relationShipScore));
        jhScl90Jgb.setQpzz(String.valueOf(obsessiveScore));
        jhScl90Jgb.setKb(String.valueOf(terrorScore));
        jhScl90Jgb.setDd(String.valueOf(hostileScore));
        jhScl90Jgb.setJl(String.valueOf(anxietyScore));
        jhScl90Jgb.setCsjg(sb.toString());
        jhScl90Jgb.setScbj(false);
        jhScl90Jgb.setSjc(new Date());
        jhScl90JgbRepository.save(jhScl90Jgb);


    }

    private double sum(String[] answerArr, int[] index) {
        double score = 0;
        for (int i = 0; i < index.length; i++) {
            score += Integer.parseInt(answerArr[index[i] - 1]);
        }
        return score;
    }

    private String getSingleResult(double avg, String[] type) {
        int index = (int) Math.round(avg);
        return type[index];
    }

    private static final String RESULT_START = "SCL-90测试结果：\r\n";
    private static final String RESULT_COLLECT = "测验结果为：\r\n";
    private static final String RESULT_BODY = "躯  体  化：";
    private static final String RESULT_OBSESSIVE = "强迫症状：";
    private static final String RESULT_RELATION = "人际关系：";
    private static final String RESULT_DEPRESSION = "抑       郁：";
    private static final String RESULT_ANXIETY = "焦       虑：";
    private static final String RESULT_HOSTILE = "敌       对：";
    private static final String RESULT_TERROR = "恐       怖：";
    private static final String RESULT_PARANOID = "偏       执：";
    private static final String RESULT_PSYCHOSIS = "精神病性：";
    private static final String RESULT_OTHER = "睡眠饮食：";

    private static final String WRAP = "\r\n";


    // 躯体化、强迫症状、人际关系敏感、抑郁、焦虑、敌对、恐怖、偏执及精神病性。
    private static final int[] BODY_INDEX = {1, 4, 12, 27, 40, 42, 48, 49, 52, 53, 56, 58};
    private static final int[] OBSESSIVE_INDEX = {3, 9, 10, 28, 38, 45, 46, 51, 55, 65};
    private static final int[] RELATIONSHIP_INDEX = {6, 21, 34, 36, 37, 41, 61, 69, 73};
    private static final int[] DEPRESSION_INDEX = {5, 14, 15, 20, 22, 26, 29, 30, 31, 32, 54, 71, 79};
    private static final int[] ANXIETY_INDEX = {2, 17, 23, 33, 39, 57, 72, 78, 80, 86};
    private static final int[] HOSTILE_INDEX = {11, 24, 63, 67, 74, 81};
    private static final int[] TERROR_INDEX = {13, 25, 47, 50, 70, 75, 82};
    private static final int[] PARANOID_INDEX = {8, 18, 43, 68, 76, 83};
    private static final int[] PSYCHOSIS_INDEX = {7, 16, 35, 62, 77, 84, 85, 87, 88, 90};
    private static final int[] OTHER_INDEX = {19, 44, 59, 60, 64, 66, 89};
    private static final String OTHER_RESULT_WELL = "饮食睡眠良好；\r\n";
    private static final String[] OTHER_RESUTL = {OTHER_RESULT_WELL, OTHER_RESULT_WELL,
            OTHER_RESULT_WELL, "轻微饮食睡眠不正常；\r\n", "中度饮食睡眠不正常；\r\n", "重度饮食睡眠不正常；\r\n"};

    private static final String PSYCHOSIS_RESULT_WELL = "精神症状良好,无显著精神病理表现；\r\n";
    private static final String[] PSYCHOSIS_RESULT = {PSYCHOSIS_RESULT_WELL, PSYCHOSIS_RESULT_WELL,
            PSYCHOSIS_RESULT_WELL, "轻度精神性阳性症状；\r\n", "中度精神阳性症状，包括凭空闻声，内心想法没说出来就被别人知道了、孤僻、情感退缩等；\r\n",
            "重度精神阳性症状，包括凭空闻声，内心想法没说出来就被别人知道了、孤僻、情感退缩等；\r\n"};

    private static final String PARANOID_RESUTL_WELL = "无显著偏执现象；\r\n";
    private static final String[] PARANOID_RESUTL =
            {PARANOID_RESUTL_WELL, PARANOID_RESUTL_WELL, PARANOID_RESUTL_WELL,
                    "轻度疑心重，坚信周围环境中的一些与他不相关的现象均与他有关；\r\n", "中度疑心病,常认为别人的言行均在含沙射影、指桑骂槐，或认为别人没有对其成绩作出正确评价；\r\n",
                    "重度偏执,常认为别人的言行均在含沙射影、指桑骂槐，或认为别人没有对其成绩作出正确评价,固执；\r\n"};

    private static final String TERROR_RESULT_WELL = "没有非寻常的恐怖情绪；\r\n";
    private static final String[] TERROR_RESULT = {TERROR_RESULT_WELL, TERROR_RESULT_WELL,
            TERROR_RESULT_WELL, "轻度恐惧情绪和紧张不安，导致脸红、气促、出汗、心悸、恶心、无力；\r\n", "中度敌对情绪,表现出脾气大、易激惹、好与人吵；\r\n",
            "重度恐惧情绪和紧张不安，导致脸红、气促、出汗、心悸、恶心、无力，甚至昏厥等症状；\r\n"};

    private static final String HOSTILE_RESULT_WELL = "无显著敌对现象；\r\n";
    private static final String[] HOSTILE_RESULT =
            {HOSTILE_RESULT_WELL, HOSTILE_RESULT_WELL, HOSTILE_RESULT_WELL, "轻微敌对情绪,表现出发脾气、易激惹；\r\n",
                    "中度敌对情绪,表现出脾气大、易激惹、好与人吵；\r\n", "重度敌对情绪,表现出脾气大、易激惹、好与人吵，有伤人毁物的冲动；\r\n"};

    private static final String ANXIETY_RESULT_WELL = "无焦虑症状；\r\n";
    private static final String[] ANXIETY_RESULT = {ANXIETY_RESULT_WELL, ANXIETY_RESULT_WELL,
            ANXIETY_RESULT_WELL, "轻微抑郁,表现有轻微症状如：情绪低落、兴趣减少、精力减少、自卑自责；\r\n",
            "中度焦虑,表现出紧张不安、做事没有耐心、遇事易往坏处想、或坐卧不宁，担心飞来横祸，常伴有心悸心慌、胸闷气促、口干等躯体不适；\r\n",
            "重度焦虑,没有明确原因的紧张不安、做事没有耐心、遇事易往坏处想、坐卧不宁，担心飞来横祸，常伴有心悸心慌、胸闷气促、口干等躯体引发肢体发抖、肌肉紧张性疼痛等；\r\n"};

    private static final String DEPRESSION_RESULT_WELL = "无抑郁症状；\r\n";
    private static final String[] DEPRESSION_RESULT =
            {DEPRESSION_RESULT_WELL, DEPRESSION_RESULT_WELL, DEPRESSION_RESULT_WELL,
                    "轻微抑郁,表现有轻微症状如：情绪低落、兴趣减少、精力减少、自卑自责；\r\n", "中度抑郁,表现出情绪低落、兴趣减少、精力减少、自卑自责、感觉做什么事都失去意义；\r\n",
                    "重度抑郁,表现出严重情绪低落、兴趣减少、精力减少、自卑自责、做什么事都失去意义；\r\n"};

    private static final String RELATION_RESULT_WELL = "人际关系良好；\r\n";
    private static final String[] RELATION_RESULT = {RELATION_RESULT_WELL, RELATION_RESULT_WELL,
            "人际关系轻微敏感,存在一定的不自在感和自卑感；\r\n", "人际关系中度敏感,对别人责备求全、感情容易受到伤害，尤其是在与他人相比较时比较明显；\r\n",
            "人际关系重度敏感, 对别人责备求全、感情容易极易受到伤害，尤其是在与他人相比较时更突出；\r\n",
            "人际关系重度敏感, 对别人责备求全、感情容易极易受到伤害，尤其是在与他人相比较时更突出；\r\n"};

    private static final String OBSESSIVE_RESULT_WELL = "无显著强迫症状反应；\r\n";
    private static final String[] OBSESSIVE_RESULT = {OBSESSIVE_RESULT_WELL, OBSESSIVE_RESULT_WELL,
            OBSESSIVE_RESULT_WELL, "表现为小心多疑、做事要求完美、犹豫不决；\r\n", "中度强迫症，具有强迫观念或强迫动作和行为；\r\n",
            "重度强迫症，表现为多疑、犹豫不决，具有强烈的强迫观念或强迫行为,患者自己因此紧张不安，十分痛苦；\r\n"};

    private static final String BODY_RESULT_WELL = "主观身体状况正常；\r\n";
    private static final String[] BODY_RESULT = {BODY_RESULT_WELL, BODY_RESULT_WELL, BODY_RESULT_WELL,
            "主观身体状况轻微不适应,如轻微头疼头昏、胃不舒服、身体发麻、乏力等；\r\n", "主观身体状况中度不适应,如伴有头疼头昏、呼吸困难、胸闷、胃不舒服、身体发麻、乏力等症状；\r\n",
            "主观身体状况重度不适应,如头疼头昏、呼吸困难、胸闷、胃不舒服、身体疲惫等症状；\r\n"};

    private static final String TEST_TYPE = "2";

    /**
     * 按照日期+6位自增长整数组成id.
     *
     * @param date 时间
     * @return 作业编号
     */
    public static String convert2Id12(Date date) {
        if (date == null) {
            return null;
        }
        return DateFormatUtils.format(date, "yyMMdd")
                + String.format("%06x", nextInc.incrementAndGet() & 0x00FFFFFF);
    }

    private static AtomicInteger nextInc = new AtomicInteger((new java.util.Random()).nextInt());
}
